package com.cube.share.sms.service;

import com.cube.share.base.templates.CustomException;
import com.cube.share.sms.config.SmsConfig;
import com.cube.share.sms.constant.SmsInfo;
import com.cube.share.sms.constant.SmsSendRejectStrategyEnum;
import com.cube.share.sms.factory.SmsSendRejectStrategyFactory;
import com.cube.share.sms.handler.DefaultSmsTemplatePlaceHolderHandler;
import com.cube.share.sms.handler.SmsTemplatePlaceHolderHandler;
import com.cube.share.sms.model.param.SmsContext;
import com.cube.share.sms.model.param.SmsSendParam;
import com.cube.share.sms.strategy.SmsTemplateContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author cube.li
 * @date 2021/9/4 9:03
 * @description 短信服务
 */
@Service
@Slf4j
public class SmsService {

    @Resource
    private SmsConfig smsConfig;

    @Resource
    private SmsApi smsApi;

    private SmsTemplatePlaceHolderHandler placeHolderHandler;

    @PostConstruct
    public void init() {
        SmsSendRejectStrategyEnum rejectStrategyEnum = smsConfig.getDefaultRejectStrategyEnum();
        if (rejectStrategyEnum == null) {
            rejectStrategyEnum = SmsSendRejectStrategyEnum.TOTALLY_MATCH;
        }
        placeHolderHandler =
                new DefaultSmsTemplatePlaceHolderHandler(SmsSendRejectStrategyFactory.getStrategy(rejectStrategyEnum));
    }

    public void send(SmsSendParam param) {
        String templateContent = smsConfig.getTemplates().get(param.getTemplateCode());
        if (templateContent == null) {
            throw new CustomException("不正确的短信模板");
        }
        SmsTemplateContext templateContext = SmsTemplateContext.from(templateContent, param.getTemplateCode());
        String sendContent = placeHolderHandler.handle(templateContext, param.getParameter());
        SmsContext smsContext = new SmsContext();
        smsContext.setContent(sendContent);
        smsContext.setMobile("1341234124");
        SmsInfo.from(smsContext, templateContext);
        smsApi.sendSms(sendContent, "1341234124");
    }
}
